<?php

/*
 * ClassName: DataProc fro adodb
 * Parameter: path;
 * Parameter: down;
 * Parameter: dbName;
 * Parameter: proc;
 * Date: 2007:04:13
 */

class DataProc{

	public $fileName;
	protected $path;
	protected $conn;
	protected $dbName;
	protected $arrRecord;
		
	public function DataProc($conn,$path,$down="true",$dbName="kkyoo_music",$proc="true"){
		$this -> path = $path;
		$this -> conn = $conn;
		$this -> dbName = $dbName;
		$proc == "true" ? $this -> BackUp($down) : $this -> Restore();
	}
	
	protected function BackUp($down){
		$query = "SHOW TABLE STATUS FROM `".$this -> dbName."`";
		if($tblResult = $this -> conn -> Execute($query)){
			while($tblArrRow = $tblResult -> FetchRow()){
				$sql .= $this -> BackTable($tblArrRow["Name"]);
				if($fieldResult = $this -> conn -> Execute("SELECT * FROM ".$tblArrRow["Name"])){
					while($this -> arrRecord = $fieldResult -> FetchRow()){
						$sql .= $this -> BackField($tblArrRow["Name"],$fieldResult -> FieldCount());
					}
				}
			}
			$down == "true" ? $this -> DownFile($sql) : $this -> SaveFile($sql);
		}
	}
	
	protected function BackTable($table){
		$query = "DROP TABLE IF EXISTS `".$table."`;\r\n";
		if($result = $this -> conn -> Execute("SHOW CREATE TABLE ".$table)){
			$arrRow = $result -> FetchRow();
			$tmp .= preg_replace("/\n/","",$arrRow["Create Table"]);
			return $query .= $tmp.";\r\n";
		}
	}
	
	protected function BackField($table,$fieldNum){
		$query = "INSERT INTO ".$table." VALUES(";
		for($i=0;$i<$fieldNum;$i++){
			$query .= "'".mysql_escape_string($this -> arrRecord[$i])."',";
		}
		return $query = substr($query,0,strlen($query)-1).");\r\n";
	}
	
	protected function DownFile($sql){
		$fileName = date("Y-m-d H-i-s",time()).".sql";
		ob_end_clean();
		header("Content-Encoding: none");
		header("Content-Type: ".(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ? 'application/octetstream' : 'application/octet-stream'));
		header("Content-Disposition: ".(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ? 'inline; ' : 'attachment; ')."filename=".$fileName);
		header("Content-Length: ".strlen($sql));
		header("Pragma: no-cache");
		header("Expires: 0");
		echo $sql;
		$tmp=ob_get_contents();
		ob_end_clean();
	}

	protected function SaveFile($sql){
		$fileName = date("Y-m-d H-i-s",time()).".sql";
		if(!file_exists($this -> path)){
			mkdir($this -> path,"0777");
		}
		$fp = fopen($this -> path."/".$fileName,"w+");
		fwrite($fp,$sql);
		$this -> fileName = $fileName;
	}
	
	protected function Restore(){
		$arrSql = file($this -> path);
		foreach($arrSql as $sql){
			$this -> conn -> Execute($sql);
		}
	}
}

?>